package com.yanqu.road.tools;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

public class ExcelTableMapper {
    /**
     * excel文件和数据库表的映射
     * key: excel名称
     * value：数据库表名
     */
    private static Map<String, String> fileMapperMap = new HashMap<>();
    /**
     * excel文件对应的配置管理类
     */
    private static Map<String, String> fileMgrClassMapperMap = new HashMap<>();

    public static Map<String, String> getFileMapperMap() {
        return fileMapperMap;
    }

    public static Map<String, String> getFileMgrClassMapperMap() {
        return fileMgrClassMapperMap;
    }

    public static void initMapper(String file) {
        // 读取xml文件
        BufferedReader fileReader;
        try {
            fileReader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file), "UTF-8"));
            BufferedReader reader = new BufferedReader(fileReader);
            try {
                SAXReader saxReader = new SAXReader();
                Document doc = saxReader.read(reader);
                Element root = doc.getRootElement();
                for (Iterator<Element> it = root.elementIterator(); it.hasNext();) {
                    Element excel = it.next();
                    for (Iterator<Element> iter = excel.elementIterator(); iter.hasNext();) {
                        Element childExcel = iter.next();
                        String resource = childExcel.attributeValue("resource");
                        if (resource != null && 0 != resource.length()) {
                            String tableName = childExcel.attributeValue("target");
                            String excelName = excel.attributeValue("file_name").trim();
                            fileMapperMap.put(excelName, tableName);
                        }

                        String mgr_name = childExcel.attributeValue("mgr_name");
                        if (mgr_name != null && 0 != mgr_name.length()) {
                            String mgr_class = childExcel.attributeValue("target");
                            String excelName = excel.attributeValue("file_name").trim();
                            fileMgrClassMapperMap.put(excelName, mgr_class);
                        }
                    }
                }
            } catch (Exception e) {
               e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
